package com.booktrade.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booktrade.dto.OrderDTO;
import com.booktrade.dto.OrderItemDTO;
import com.booktrade.dto.OrderRequestDTO;
import com.booktrade.entity.Books;
import com.booktrade.entity.Cart;
import com.booktrade.entity.OrderItems;
import com.booktrade.entity.Orders;
import com.booktrade.mapper.BooksMapper;
import com.booktrade.mapper.OrderItemsMapper;
import com.booktrade.mapper.OrdersMapper;
import com.booktrade.mapper.UsersMapper;
import com.booktrade.service.*;
import com.booktrade.vo.ItemVo;
import com.booktrade.vo.OrderVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表，存储用户购买的订单信息 服务实现类
 * </p>
 */
@Service
@RequiredArgsConstructor
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    private final OrdersMapper orderMapper;
    private final OrderItemsMapper orderItemsMapper;
    private final ICartService cartService;
    private final BooksMapper booksMapper;
    private final UsersMapper usersMapper;


    @Override
    public List<OrderVo> getOrdersByBuyerId(Integer buyerId,String status) {
        // 根据买家ID查询订单
        List<Orders> orders = orderMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getBuyerId,buyerId)
                .eq(status!=null && !"".equals(status),Orders::getStatus,status)
                .orderByDesc(Orders::getCreatedAt));
        return getOrderVos(orders);
    }

    @Override
    public boolean confirmReceipt(Integer orderId, Integer buyerId) {
        // 查询订单并验证是否为该买家的订单
        Orders order = orderMapper.selectById(orderId);
        if (order == null || !order.getBuyerId().equals(buyerId)) {
            return false;
        }
        // 更新订单状态为已收货
        order.setStatus("已收货");
        return orderMapper.updateById(order) == 1;
    }

    @Override
    public List<OrderVo> getOrdersBySellerId(Integer sellerId,String status) {
        // 根据卖家ID查询订单
        List<Orders> orders = orderMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getSellerId,sellerId)
                .eq(status!=null && !"".equals(status),Orders::getStatus,status)
                .orderByDesc(Orders::getCreatedAt));
        return getOrderVos(orders);
    }

    private List<OrderVo> getOrderVos(List<Orders> orders) {
        List<OrderVo> orderVoList = BeanUtil.copyToList(orders, OrderVo.class);
        orderVoList = orderVoList.stream().map(o -> {
            o.setSellerName(usersMapper.selectById(o.getSellerId()).getUsername());
            o.setBuyerName(usersMapper.selectById(o.getBuyerId()).getUsername());
            List<OrderItems> orderItems = orderItemsMapper.selectList(new LambdaQueryWrapper<OrderItems>().eq(OrderItems::getOrderId, o.getId()));
            //继续遍历订单项，封装书籍信息
            List<ItemVo> itemVoList = orderItems.stream().map(item -> {
                ItemVo itemVo = BeanUtil.copyProperties(item, ItemVo.class);
                Books book = booksMapper.selectById(item.getBookId());
                if (book != null) {
                    BeanUtil.copyProperties(book, itemVo);
                }
                return itemVo;
            }).collect(Collectors.toList());
            o.setItemVoList(itemVoList);
            return o;
        }).collect(Collectors.toList());
        return orderVoList;
    }

    @Override
    public boolean shipOrder(Integer orderId, Integer sellerId) {
        // 查询订单并验证是否为该卖家的订单
        Orders order = orderMapper.selectById(orderId);
        if (order == null || !order.getSellerId().equals(sellerId)) {
            return false;
        }
        // 更新订单状态为已发货
        order.setStatus("待评价");
        return orderMapper.updateById(order) == 1;
    }

    @Override
    public boolean requestRefund(Integer orderId, Integer buyerId) {
        // 查询订单并验证是否为该买家的订单
        Orders order = orderMapper.selectById(orderId);
        if (order == null || !order.getBuyerId().equals(buyerId)) {
            return false;
        }
        // 更新订单状态为退款申请中
        order.setStatus("退款申请中");
        return orderMapper.updateById(order) == 1;
    }

    @Override
    @Transactional
    public List<Integer> saveOrder(OrderRequestDTO orderDTO, Integer buyerId) {
        List<Integer> orderIds = new ArrayList<>(); // 用于保存所有订单ID

        // 初始化订单项按卖家分组
        Map<Integer, List<OrderItemDTO>> itemsGroupedBySeller = orderDTO.getItems().stream()
                .collect(Collectors.groupingBy(OrderItemDTO::getSellerId));

        // 遍历每个卖家创建对应的订单
        for (Map.Entry<Integer, List<OrderItemDTO>> entry : itemsGroupedBySeller.entrySet()) {
            Integer sellerId = entry.getKey();
            List<OrderItemDTO> items = entry.getValue();

            // 初始化当前订单的总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            Orders order = new Orders();
            List<OrderItems> orderItemsList = new ArrayList<>();

            for (OrderItemDTO item : items) {
                Books book = booksMapper.selectById(item.getBookId());
                if (book == null) {
                    throw new RuntimeException("书籍ID：" + item.getBookId() + " 不存在");
                }

                BigDecimal itemTotalPrice = book.getPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
                totalAmount = totalAmount.add(itemTotalPrice);

                OrderItems orderItem = new OrderItems();
                orderItem.setBookId(item.getBookId());
                orderItem.setQuantity(item.getQuantity());
                orderItem.setPrice(book.getPrice());
                orderItemsList.add(orderItem);
            }

            // 应用优惠金额 (按比例分配优惠金额到每个订单)
            BigDecimal discountPerOrder = orderDTO.getDiscount().divide(BigDecimal.valueOf(itemsGroupedBySeller.size()), RoundingMode.HALF_UP);
            totalAmount = totalAmount.subtract(discountPerOrder);

            // 创建订单对象
            order.setBuyerId(buyerId);
            order.setSellerId(sellerId);
            order.setTotalPrice(totalAmount);
            order.setStatus("待付款");
            orderMapper.insert(order);

            // 将订单ID添加到返回列表中
            orderIds.add(order.getId());

            // 将订单ID设置到订单项并插入到数据库
            for (OrderItems orderItem : orderItemsList) {
                orderItem.setOrderId(order.getId());
                orderItemsMapper.insert(orderItem);
            }
        }

        // 清空购物车中结算的商品
        List<Integer> bookIdsToRemove = orderDTO.getItems().stream()
                .map(OrderItemDTO::getBookId)
                .collect(Collectors.toList());

        cartService.remove(new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, buyerId)
                .in(Cart::getBookId, bookIdsToRemove)); // 删除购物车中结算的 bookId

        return orderIds; // 返回所有订单ID给前端
    }




    private OrderDTO convertToDTO(Orders order) {
        // 将 Order 转换为 OrderDTO
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setId(order.getId());
        orderDTO.setBuyerId(order.getBuyerId());
        orderDTO.setSellerId(order.getSellerId());
        orderDTO.setTotalPrice(order.getTotalPrice());
        orderDTO.setStatus(order.getStatus());
        orderDTO.setCreatedAt(order.getCreatedAt());
        orderDTO.setUpdatedAt(order.getUpdatedAt());

        // 查询订单项并设置
        List<OrderItems> orderItems = orderItemsMapper.selectByOrderId(order.getId());
        orderDTO.setOrderItems(orderItems);
        return orderDTO;
    }
}
